package com.cheche.dn.monitor;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * Service 调用时间监控
 * Created by cheshun on 15/11/5.
 */
@Aspect
@Order(Ordered.HIGHEST_PRECEDENCE)
@Component
public class ServiceMonitor {
    private static final Logger logger = LoggerFactory.getLogger(ServiceMonitor.class);

    @Pointcut("execution(public * com.cheche.dn..*Service.*(..))")
    public void service() {
    }

    @Around("service()")
    public Object service(ProceedingJoinPoint pjp) throws Throwable {
        long start = System.currentTimeMillis();
        Object obj = pjp.proceed();
        long end = System.currentTimeMillis();
        long time = end - start;
        if (time > 100) {
            Signature signature = pjp.getSignature();
            Object[] args = pjp.getArgs();
            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < args.length; i++) {
                builder.append(args[i]);
                if (i != args.length - 1) {
                    builder.append(", ");
                }
            }
            logger.warn("the method is so slow [{}], {}({})", time,
                    signature.getDeclaringTypeName() + "." + signature.getName(), builder.toString());
        }
        return obj;
    }

}
